<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/14
 * Time: 15:01
 */

namespace App\Rep;


use App\Events\OrderChildAllDone;
use App\Exceptions\ApiException;
use App\Models\FinishProduct;
use App\Models\ModelFields;
use App\Models\ModelNumberColor;
use App\Models\Models;
use App\Models\Order;
use App\Models\OrderAudit;
use App\Models\OrderAuditLog;
use App\Models\OrderChild;
use App\Models\OrderKucunLog;
use App\Models\OrderSecond;
use App\Models\Product;
use App\Models\ProductJobType;
use App\Models\SemiFinishProduct;
use App\Models\Specification;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use function Symfony\Component\Routing\Matcher\Dumper\export;

class OrderRep
{

    /**
     * 获取订单列表
     * @param $params
     * @return mixed
     */
    public function getOrderListRep($params){
        $list = Order::Search($params)
            ->with(['color'=>function($q){
                return $q->select('id','color');
            },'product'=>function($q){
                return $q->select('id','product_name');
            },'customer'=>function($q){
                return $q->select('id','customer_name','customer_address','balance','contact_phone');
            },'modelNumber'=>function($q){
                return $q->select('id','model_number','file_id')->with(['specification','file']);
            },'orderChild'=>function($q){
                return $q->with(['job_type','employee']);
            },'specification'=>function($q){
                return $q->select('id','specification');
            },'accountExecutive'=>function($q){
                return $q->select('id','company_name','phone');
            },'finish_product'=>function($q){
                return $q->select('order_id','warehouse_id','goods_shelf_id');
            },'admin_user'=>function($q){
                return $q->select('id','company_name');
            },'order_second'=>function($q){
                $q->with(['models'=>function($q){
                    $q->select('modelid','modelname','pid');
                },'product'=>function($q){
                    $q->select('id','product_name');
                },'model_number'=>function($q){
                    $q->select('id','model_number');
                },'specification'=>function($q){
                    $q->select('id','specification');
                },'color'=>function($q){
                    $q->select('id','color');
                }]);
            }])
            ->orderBy('id','desc')
            ->paginate($params['per_page']??10)->toArray();
        $data = $list['data'];
        $data = $this->getModelFieldData($data);
        $list['data'] = $data;
        return $list;
    }

    /**
     * 获取模型里的数据
     * @param $data
     * @return array
     */
    public function getModelFieldData($data){
        if($data){
            foreach($data as $k=>$v){
                $product_id = $v['product_id'];
                $modelid = Product::where('id',$product_id)->value('modelid');
                $tablename = Models::where('modelid',$modelid)->value('tablename');
                $model_field = ModelFields::where('modelid',$modelid)->get();
                //p($model_field->toArray());
                if($model_field){
                    foreach($model_field as $kk=>$vv){
                        if(in_array($vv->formtype,['input','textarea'])){
                            $data[$k]['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                        }else{
                            $option_list = explode("\n",$vv->option_list);
                            $option_arr = [];
                            if($option_list){
                                foreach($option_list as $key=>$val){
                                    $option = explode("|",rtrim($val));
                                    $option_arr[$option[1]] = $option[0];
                                }
                                $field_key = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                                if($field_key){
                                    $data[$k]['models_field'][$vv->field] = $option_arr[$field_key];
                                }else{
                                    $data[$k]['models_field'][$vv->field] = null;
                                }
                            }else{
                                $data[$k]['models_field'][$vv->field] = null;
                            }

                        }
                    }
                }
            }
        }
        return $data;
    }

    /**
     * 添加订单
     * 选择数量，批量添加订单
     * @param $params
     */
    public function createOrderRep($params){
        //p($params);
        DB::beginTransaction();
        try {
            foreach($params['order_data'] as $k=>$v){
                $pid = $v['pid'];
                $num = $v['num'];
                $modelRep = new ModelRep();
                //获取产品添加字段
                $field_arr = $modelRep->getProductFieldListRep($v['modelid']);

                $addOrderParentData = [];
                //模型添加的字段
                $addOrderParentDatas = [];
                foreach($field_arr as $kk=>$vv){
                    if($vv['show'] == 1){
                        if(isset($v[$vv['field']])){
                            if($vv['is_default'] == 1){
                                $addOrderParentData[$vv['field']] = $v[$vv['field']]??'';
                            }else{
                                $addOrderParentDatas[$vv['field']] = $v[$vv['field']]??"";
                            }
                        }
                    }
//                    $addOrderParentData['is_chuangtougui'] = $v['is_chuangtougui'];
//                    $addOrderParentData['is_chuangtou'] = $v['is_chuangtou'];
//                    $addOrderParentData['is_chuangbian'] = $v['is_chuangbian'];
                    $addOrderParentData['pid'] = $pid;
                    $addOrderParentData['modelid'] = $v['modelid'];
                    $addOrderParentData['user_id'] = $params['user_id'];
                    $addOrderParentData['created_at'] = date("Y-m-d H:i:s");
                    $addOrderParentData['serial_number'] = $this->automaticGenerationSerialNumberRep();
                    $addOrderParentData['order_number'] = $this->automaticGenerationOrderNumberRep();
                }
                //添加主订单
                $order_id = $this->addOrderRep($addOrderParentData,$addOrderParentDatas);
                $order = Order::find($order_id);
                $SecondRep = new OrderSecondRep();
                if($pid == 1){
                    //添加成品
                    //是否补录订单
                    if($v['is_replenishment'] == 2){
                        //订单审核
                        //判断审核流程，是否对订单进行审核
                        $orderAuditList = self::judgeOrderAudit();
                        if($orderAuditList){
                            //添加审核记录
                            self::createOrderAudit($orderAuditList,$order_id,$params['user_id'],$params['username'],$params['role_id'],$params['role_name'],$v['remark']);
                        }
                        //添加半成品工序;
                        foreach($v['semi_product'] as $kk=>$vv){
                            if($vv['num'] != ''){
                                $nums = $vv['num'];
                                $total_num = $vv['num'] * $num;
                            }else{
                                $nums = $num;
                                $total_num = $num;
                            }
                            if($vv['is_kucun'] == 1){
                                //库存充足
                                $order_second_id = $SecondRep->addOrderSecondRep(
                                    $order_id,
                                    $vv['modelid'],
                                    $vv['product_id'],
                                    $vv['model_number_id']??'',
                                    $v['specification_id'],
                                    '',
                                    $order->is_replenishment,
                                    $order->is_stock_up,
                                    0,
                                    $total_num,
                                    1,
                                    $vv['warehouse_id'],
                                    $vv['goods_shelf_id'],
                                    2,
                                    $vv['warehouse_location_id']??'',
                                );
                                //使用库存
                                $this->useInventoryRep(
                                    $nums,
                                    $vv['product_id'],
                                    $vv['model_number_id'],
                                    $vv['specification_id']??'',
                                    '',
                                    $order_id,
                                    $vv['warehouse_id'],
                                    $vv['goods_shelf_id'],
                                    $order_second_id
                                );
                            }else{
                                $order_second_id = $SecondRep->addOrderSecondRep(
                                    $order_id,
                                    $vv['modelid'],
                                    $vv['product_id'],
                                    $vv['model_number_id']??'',
                                    $v['specification_id']??0,
                                    0,
                                    $order->is_replenishment,
                                    $order->is_stock_up,
                                    $nums,
                                    $total_num,
                                    2,
                                    $vv['warehouse_id'],
                                    $vv['goods_shelf_id'],
                                    2,
                                    $vv['warehouse_location_id']??'',
                                );
                            }
                            //加入半成品库
                            $this->selectOrderChildStatusBySecondId($order_id,$order_second_id);
                        }

                    }else{
                        //成品，补录，添加到成品库
                        $this->selectOrderChildStatusByOrderId($order_id);
                    }
                }else{
                    //添加半成品
                    //是否补录订单
                    if($v['is_replenishment'] == 2){
                        //订单审核
                        //判断审核流程，是否对订单进行审核
                        $orderAuditList = self::judgeOrderAudit();
                        if($orderAuditList){
                            //添加审核记录
                            self::createOrderAudit($orderAuditList,$order_id,$params['user_id'],$params['username'],$params['role_id'],$params['role_name'],$v['remark']);
                        }
                        if($v['is_kucun'] == 1){
                            //库存充足
                            $order_second_id = $SecondRep->addOrderSecondRep(
                                $order_id,
                                $v['modelid'],
                                $v['product_id'],
                                $v['model_number_id']??'',
                                $v['specification_id'],
                                '',
                                $order->is_replenishment,
                                $order->is_stock_up,
                                0,
                                $num,
                                1,
                                $v['warehouse_id'],
                                $v['goods_shelf_id'],
                                2,
                                $v['warehouse_location_id']??'',
                            );
                            //使用库存
                            $shengchan_num = $this->useInventoryRep(
                                $num,
                                $v['product_id'],
                                $v['model_number_id'],
                                $v['specification_id']??'',
                                '',
                                $order_id,
                                $v['warehouse_id'],
                                $v['goods_shelf_id'],
                                $order_second_id
                            );
                        }else{

                            $order_second_id = $SecondRep->addOrderSecondRep(
                                $order_id,
                                $v['modelid'],
                                $v['product_id'],
                                $v['model_number_id']??'',
                                $v['specification_id']??"",
                                $v['color_id']??'',
                                $order->is_replenishment,
                                $order->is_stock_up,
                                $num,
                                $num,
                                2,
                                $v['warehouse_id'],
                                $v['goods_shelf_id'],
                                2,
                                $v['warehouse_location_id']??'',
                            );
                        }
                        //$this->selectOrderChildStatusBySecondId($order_id,$order_second_id);
                    }else{
                        //加入半成品库
                        $order_second_id = $SecondRep->addOrderSecondRep(
                            $order_id,
                            $v['modelid'],
                            $v['product_id'],
                            $v['model_number_id']??'',
                            $v['specification_id']??"",
                            $v['color_id']??'',
                            $order->is_replenishment,
                            $order->is_stock_up,
                            $num,
                            $num,
                            2,
                            $v['warehouse_id'],
                            $v['goods_shelf_id'],
                            2,
                            $v['warehouse_location_id']??'',
                        );
                        $this->selectOrderChildStatusBySecondId($order_id,$order_second_id);
                    }
                }
            }
            DB::commit();
            return ['code'=>0,'data'=>[],'msg'=>'success'];
        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$exception->getMessage()];
        }
    }

    //使用库存
    //库存充足，返回生产数量为0
    //库存不足，库存减去下单数量，返回绝对值为生产数量
    public function useInventoryRep($num,$product_id,$model_number_id,$specification_id,$color_id,$order_id,$warehouse_id,$goods_shelf_id,$order_second_id){

        //初始化库存
        //$this->releaseOrderKucunLog($order_id);

        $semiRep = new SemiFinishProductRep();
        $total_num = $num;//下单的总件数
        //从半成品备货库中获取备货ID
        $semi_id_arr = $semiRep->getInventoryIdRep(
            $product_id,
            $model_number_id,
            $specification_id,
            $warehouse_id,
            $goods_shelf_id
        );
        Log::channel('kucunlog')->info("查询条件:".json_encode([
                $product_id,
                $model_number_id,
                $specification_id,
                $warehouse_id,
                $goods_shelf_id]));
        Log::channel('kucunlog')->info("从半成品备货库中获取备货ID:".implode(',',$semi_id_arr));

        if(count($semi_id_arr)<=0){
            throw new ApiException(20001,'库存不足');
        }

        if($total_num>1){
            $rand_key = array_rand($semi_id_arr,$total_num);
            foreach($rand_key as $item=>$value){
                $semi_id_arrs[] = $semi_id_arr[$value];
            }
        }else{
            $rand_key = array_rand($semi_id_arr);
            $semi_id_arrs[] = $semi_id_arr[$rand_key];
        }

        foreach($semi_id_arrs as $k=>$v){
            OrderKucunLog::insert([
                'order_id'=>$order_id,
                'order_second_id'=>$order_second_id,
                'semi_ids'=>$v
                ]
            );
            SemiFinishProduct::where('id',$v)->update(['is_del'=>1]);
        }

        $product_num = 0;
        return $product_num;
    }

    /**
     * 初始化库存
     * 订单编辑时，需要先初始化半成品库存（将新增订单时使用的库存初始化）
     * @param $order_id
     * @return void
     */
    public function releaseOrderKucunLog($order_id,$order_second_id){
        //OrderKucunLog：使用库存的记录
        $semi_ids = OrderKucunLog::where('order_id',$order_id)
            ->where('order_second_id',$order_second_id)
            ->pluck('semi_ids')->toArray();
        if(!empty($semi_ids)){
            //释放库存
            SemiFinishProduct::whereIn('id',$semi_ids)->update(
                [
                    'is_del'=>2,
                    'production_order_child_id'=>''
                ]
            );
        }
        OrderKucunLog::where('order_id',$order_id)
            ->where('order_second_id',$order_second_id)
            ->delete();
        return $semi_ids;
    }

    /**
     * 初始化审核记录
     * @param $order_id
     * @return void
     */
    public function releaseOrderAuditLog($order_id){
        OrderAuditLog::where('order_id',$order_id)->delete();
    }

    /**
     * 初始化OrderSecond
     * @param $order_id
     * @return void
     */
    public function releaseOrderSecond($order_id){
        OrderSecond::where('order_id',$order_id)->delete();
    }


    /**
     * 编辑订单
     */
    public function alertOrdersRep($params){
        DB::beginTransaction();
        try {
            $order_data = $params['order_data'];
            $order_id = $order_data['id'];
            $pid = $order_data['pid'];
            $num = $order_data['num'];
            $modelRep = new ModelRep();
            //获取产品添加字段
            $field_arr = $modelRep->getProductFieldListRep($order_data['modelid']);
            //p($field_arr);
            $addOrderParentData = [];
            $addOrderParentDatas = [];
            foreach($field_arr as $kk=>$vv){
                if($vv['show'] == 1){
                    if(isset($vv['field'])){
                        if($vv['is_default'] == 1){
                            $addOrderParentData[$vv['field']] = $order_data[$vv['field']];
                        }else{
                            $addOrderParentDatas[$vv['field']] = $order_data[$vv['field']];
                        }
                    }
                }

                $addOrderParentData['pid'] = $pid;
                $addOrderParentData['modelid'] = $order_data['modelid'];
                $addOrderParentData['user_id'] = $params['user_id'];
                $addOrderParentData['created_at'] = date("Y-m-d H:i:s");
                unset($addOrderParentData['serial_number']);
                unset($addOrderParentData['order_number']);
            }
            //p($addOrderParentData);
            $order_id = $this->updateOrderRep($order_id,$addOrderParentData,$addOrderParentDatas);
            $order = Order::find($order_id);

            $SecondRep = new OrderSecondRep();

            //是否补录订单
            if($order_data['is_replenishment'] != 1){
                //订单审核
                //判断审核流程，是否对订单进行审核
                $orderAuditList = self::judgeOrderAudit();
                if($orderAuditList){
                    //添加审核记录
                    self::createOrderAudit($orderAuditList,$order_id,$params['user_id'],$params['username'],$params['role_id'],$params['role_name'],$order_data['remark']);
                }
            }
            if($pid == 1){
                //添加成品
                foreach($order_data['semi_product'] as $kk=>$value){
                    if($value['is_kucun'] == 1){
                        //使用库存
                        //库存充足
                        $order_second_id = $SecondRep->addOrderSecondRep(
                            $order_id,
                            $value['modelid'],
                            $value['product_id'],
                            $value['model_number_id']??0,
                            $value['specification_id']??0,
                            $value['color_id']??0,
                            $order->is_replenishment,
                            $order->is_stock_up,
                            0,
                            $num,
                            1,
                            $value['warehouse_id'],
                            $value['goods_shelf_id'],
                            2,
                            $value['warehouse_location_id']??'',
                        );
                    }else{
                        $order_second_id = $SecondRep->addOrderSecondRep(
                            $order_id,
                            $value['modelid'],
                            $value['product_id'],
                            $value['model_number_id']??'',
                            $value['specification_id']??0,
                            0,
                            $order->is_replenishment,
                            $order->is_stock_up,
                            $value['num'],
                            $value['num'],
                            2,
                            $value['warehouse_id'],
                            $value['goods_shelf_id'],
                            2,
                            $value['warehouse_location_id']??'',
                        );
                    }
                    if($order_data['is_replenishment'] == 1){
                        $this->selectOrderChildStatusBySecondId($order_id,$order_second_id);
                    }
                }

                if($order_data['is_replenishment'] == 1){
                    $this->selectOrderChildStatusByOrderId($order_id);
                }
            }else{
                //添加半成品
                if($order_data['is_kucun'] == 1){
                    //使用库存
                    //库存充足
                    $order_second_id = $SecondRep->addOrderSecondRep(
                        $order_id,
                        $order_data['modelid'],
                        $order_data['product_id'],
                        $order_data['model_number_id']??'',
                        $order_data['specification_id'],
                        '',
                        $order->is_replenishment,
                        $order->is_stock_up,
                        0,
                        $num,
                        1,
                        $order_data['warehouse_id'],
                        $order_data['goods_shelf_id'],
                        2,
                        $order_data['warehouse_location_id']??'',
                    );
                }else{
                    $order_num = $num;
                    $total_num = $num;
                    $order_second_id = $SecondRep->addOrderSecondRep(
                        $order_id,
                        $order_data['modelid'],
                        $order_data['product_id'],
                        $order_data['model_number_id']??'',
                        $order_data['specification_id']??"",
                        $order_data['color_id']??'',
                        $order->is_replenishment,
                        $order->is_stock_up,
                        $order_num,
                        $total_num,
                        $order_data['is_kucun'],
                        $order_data['warehouse_id'],
                        $order_data['goods_shelf_id'],
                        2,
                        $order_data['warehouse_location_id']??'',
                    );
                    Log::channel('addorderlog')->info('编辑半成品，不使用库存；order_id:'.$order_id.';modelid:'.$order_data['modelid'].';product_id:'.$order_data['product_id'].';model_number_id:'.$order_data['model_number_id']);
                }
            }

            DB::commit();
            return ['code'=>0,'data'=>[],'msg'=>'success'];
        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$exception->getMessage()];
        }
    }

    public function addOrderRep($insertArr,$insertArrs){
        //p($insertArr);
        //是否备货
        if($insertArr['is_stock_up'] == 1){
            $insertArr['customer_id'] = 0;
        }
        //是否是补录订单
        if($insertArr['is_replenishment'] == 1){
            $insertArr['status'] = 1;
            $insertArr['production_status'] = 3;
        }
        //p($insertArr);
        DB::beginTransaction();
        try {
            $order_id = Order::insertGetId($insertArr);
            $model = Models::where('modelid',$insertArr['modelid'])->first();
            //p($model->tablename);
            $insertArrs['order_id'] = $order_id;
            DB::table($model->tablename)->insert($insertArrs);
            DB::commit();
            return $order_id;
        }catch(\Exception $exception){
            DB::rollBack();
            throw new ApiException(20001,'添加失败，检查流水号订单号是否重复'.$exception->getMessage());
        }

    }



    public function updateOrderRep($order_id,$insertArr,$insertArrs){
        //p($insertArrs);
        //是否备货
        if($insertArr['is_stock_up'] == 1){
            $insertArr['customer_id'] = 0;
        }
        //是否是补录订单
        if($insertArr['is_replenishment'] == 1){
            $insertArr['status'] = 1;
            $insertArr['production_status'] = 3;
        }
        $model = Models::where('modelid',$insertArr['modelid'])->first();
        Order::where('id',$order_id)->update($insertArr);
        if(!empty($insertArrs)){
            DB::table($model->tablename)->where('order_id',$order_id)->update($insertArrs);
        }
        return $order_id;
    }


    /**
     * 删除订单
     * @param $params
     */
    public function delOrderRep($id){
        try {
            DB::beginTransaction();
            $model = Order::where('id',$id)->first();
            $model->is_del = 1;
            $model->save();
            $order_second = OrderSecond::where('order_id',$id)->get();
            if($order_second->count()>0){
                foreach($order_second as $k=>$v){
                    if($v->is_kucun == 1){
                        //释放库存
                        $this->releaseOrderKucunLog($v->order_id,$v->id);
                    }
                    $v->is_del = 1;
                    $v->save();
                }
            }

            $semi = SemiFinishProduct::where('order_id')->get();
            foreach($semi as $k=>$v){
                if(!empty($v->production_order_child_id)){
                    throw new ApiException(20001,'订单的库存已被使用，无法删除');
                }
            }
            OrderChild::where('order_id',$id)->update(['is_del'=>1]);
            SemiFinishProduct::where('order_id',$id)->update(['is_del'=>1]);
            FinishProduct::where('order_id',$id)->update(['is_del'=>1]);
            DB::commit();
            return $model;
        }catch(\Exception $exception){
            DB::rollBack();
            throw new ApiException(20001,'删除失败：'.$exception->getMessage());
        }

    }

    /**
     * 审核订单
     * status 1：已审核通过2：未审核3：已审核不通过
     * @param $params
     */
    public function auditOrderRep($id,$field,$status,$remark='审核原因',$is_kucun){

        DB::beginTransaction();
        try{
            $order = Order::where('id',$id)->first();
            $orderAuditLog = OrderAuditLog::where('order_audit_name',$field)->where('order_id',$id)->first();
            //p($field);
            if($orderAuditLog->res == 1){
                return ['code'=>2001,'data'=>[],'msg'=>'审核已通过，无需再次审核'];
            }
            $order->$field = $status;
            $orderAudit = OrderAudit::where('status',1)->orderBy('sort','desc')->first();
            $last_field = $orderAudit->field_name;
            //p($last_field);
            if($field == $last_field){
                if($status == 1){
                    $order->status = 1;
                    //自动生成子订单
                    $childOrderRep = new OrderChildRep();
                    $childOrderRep->autoCreateOrderChild($order->id);
                    if($order->pid == 1){
                        //生成完子订单判断所有子订单完成情况，将订单加入成品库
                        $this->selectOrderChildStatusByOrderId($order->id);
                    }
                }
            }
            if($status == 2){
                $order->status = 3;
            }
            $order->save();
            $orderAuditLog->res = $status;
            $orderAuditLog->remark = $remark;
            $orderAuditLog->save();
            DB::commit();
            return $order;
        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$exception->getMessage()];
        }

    }

//    public function selectOrderChildStatus($order_id,$order_second_id){
//        $order = Order::where('id',$order_id)->first();
//        $order_second = OrderSecond::where('id',$order_second_id)->first();
//        $count = OrderSecond::where('order_id',$order_id)
//            ->where('order_second_id',$order_second_id)
//            ->where('status','<>',1)
//            ->count();
//        if($count == 0){
//            //加入半成品库
//            if($order->pid != 1){
//                $order->production_status = 2;
//                $order->save();
//            }
//            $order_second->production_status = 2;
//            $order_second->save();
//            $semiRep = new SemiFinishProductRep();
//            $is_del = 1;
//            if($order->is_stock_up == 1){
//                //是备货，不需要删除
//                $is_del = 2;
//            }
//            //加入半成品库
//            $semiRep->addSemiFinishProductRep(
//                $order_id,
//                $order_second_id,
//                $order->pid,
//                $order_second->product_id,
//                $order_second->model_number_id??$order->model_number_id,
//                $order_second->specification_id??$order->specification_id,
//                $order_second->color_id??$order->color_id,
//                $order_second->num,
//                $order_second->modelid,
//                $is_del,
//                $order->warehouse_id,
//                $order->goods_shelf_id,
//            );
//        }
//
//    }
    /**
     * 在子订单完成提交的时候调用,加入半成品库
     * 查询子订单状态
     */
    public function selectOrderChildStatusBySecondId($order_id,$order_second_id,$remark='半成品备注'){
        $insertArr = [];
        $order = Order::where('id',$order_id)->first();
        $product_id = $order->product_id;
        $model_number_id = $order->model_number_id;
        $specification_id = $order->specification_id;
        $color_id = $order->color_id;
        $num = $order->num;
        $modelid = $order->modelid;
            $order_second = OrderSecond::where('id',$order_second_id)->first();
            $count = OrderChild::where('order_id',$order_id)
                ->where('order_second_id',$order_second_id)
                ->where('status','<>',1)
                ->count();
            if($count == 0){
                //加入半成品库
                if($order->pid != 1){
                    $order->production_status = 2;
                    $order->save();
                }
                if($order_second){
                    $order_second->production_status = 2;
                    $order_second->save();
                    $product_id = $order_second->product_id;
                    $model_number_id = $order_second->model_number_id;
                    $specification_id = $order_second->specification_id;
                    $color_id = $order_second->color_id;
                    $num = $order_second->num;
                    $modelid = $order_second->modelid;
                }

                $semiRep = new SemiFinishProductRep();
                $is_del = 1;
                if($order->is_stock_up == 1){
                    //是备货，不需要删除
                    $is_del = 2;
                }
                //加入半成品库
                $semiRep->addSemiFinishProductRep(
                    $order_id,
                    $order_second_id??'',
                    $order->pid,
                    $product_id,
                    $model_number_id,
                    $specification_id,
                    $color_id,
                    $num,
                    $modelid,
                    $is_del,
                    $order->warehouse_id,
                    $order->goods_shelf_id,
                    $remark
                );
            }

    }

    public function selectOrderChildStatusByOrderId($order_id){
        $order = Order::where('id',$order_id)->first();
        $count = OrderChild::where('order_id',$order_id)->where('status','<>',1)->count();
        if($count == 0){
            $order_second_count = OrderSecond::where('order_id',$order_id)->whereIn('production_status',[0,1])->count();
            if($order_second_count == 0){
                $order->production_status = 3;
                $order->save();
                $finishRep = new FinishProductRep();
                //加入成品库
                $finish_id = $finishRep->addFinishProductRep(
                    $order_id,
                    $order['warehouse_id'],
                    $order['goods_shelf_id'],
                    $order['model_number_id'],
                    $order['specification_id'],
                    $order['color_id'],
                    $order['customer_id'],
                    $order['is_stock_up'],
                    $order['num']
                );
                $order_kucun_log = OrderKucunLog::where('order_id',$order_id)->first();
                if($order_kucun_log){
                    //使用了库存
                    $semi_ids = explode(',',$order_kucun_log->semi_ids);
                    SemiFinishProduct::whereIn('id',$semi_ids)->update(['finish_id'=>$finish_id,'is_del'=>1]);
                }
                SemiFinishProduct::where('order_id',$order_id)->update(['finish_id'=>$finish_id,'is_del'=>1]);
            }
        }
    }

    /**
     * 获取审核订单列表
     * @param $params
     */
    public function getAuditOrderListRep($params){
        $list = Order::Audit($params)
            ->with(['color'=>function($q){
                return $q->select('id','color');
            },'product_name'=>function($q){
                return $q->select('id','product_name');
            },'customer'=>function($q){
                return $q->select('id','customer_name');
            },'modelNumber'=>function($q){
                return $q->select('id','model_number','file_id')->with(['specification','file']);
            },'accountExecutive',
                'specification'=>function($q){
                    return $q->select('id','specification');
                },'audit_log'=>function($q){
                    $q->where('status',1);
                },'order_second'=>function($q){
                    $q->with(['models'=>function($q){
                        $q->select('modelid','modelname','pid');
                    },'product'=>function($q){
                        $q->select('id','product_name');
                    },'model_number'=>function($q){
                        $q->select('id','model_number');
                    },'specification'=>function($q){
                        $q->select('id','specification');
                    },'color'=>function($q){
                        $q->select('id','color');
                    }]);
                }])
            ->orderBy('status','asc')
            ->orderBy('id','desc')
            ->paginate($params['per_page']??10)->toArray();

        //p($list->toObject());
        $data = $list['data'];
        if($data){
            foreach($data as $k=>$v){
                $tablename = Models::where('modelid',$v['modelid'])->value('tablename');
                $model_field = ModelFields::where('modelid',$v['modelid'])->get();

                if($model_field){
                    foreach($model_field as $kk=>$vv){
                        if(in_array($vv->formtype,['input','textarea'])){
                            $data[$k]['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                        }else{
                            $option_list = explode("\n",$vv->option_list);
                            $option_arr = [];
                            foreach($option_list as $key=>$val){
                                $option = explode("|",rtrim($val));
                                $option_arr[$option[1]] = $option[0];
                            }
//                            $field_key = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
//                            $data[$k]['models_field'][$vv->field] = $option_arr[$field_key];
                        }
                    }
                }

            }
        }
        $list['data'] = $data;
        return $list;
    }

    /**
     * 获取订单审核流程
     * @param $params
     */
    static public function getOrderAuditFlowRep(){
        return OrderAudit::where('status',1)->orderBy('sort','desc')->get();
    }


    /**
     * 判断是否对订单进行审核
     * @return bool
     */
    static function judgeOrderAudit(){
        $orderAuditList = self::getOrderAuditFlowRep();
        if($orderAuditList->count()){
            return $orderAuditList;
        }
        return false;
    }

    /**
     * 添加审核记录
     * @param OrderAudit $list
     * @param $order_id
     * @param $user_id
     * @param $user_name
     * @param $role_id
     * @param $role_name
     * @param $remark
     */
    static function createOrderAudit($list,$order_id,$user_id,$user_name,$role_id,$role_name,$remark){
        foreach($list as $k=>$v){
            //添加审核记录
            OrderAuditLog::updateOrCreate(['order_id'=>$order_id,'audit_name'=>$v->audit_name],
                [
                    //'order_id'=>$order_id,
                    'user_id'=>$user_id,
                    'user_name'=>$user_name,
                    'role_id'=>$role_id,
                    'role_name'=>$role_name,
                    'order_audit_name'=>$v->field_name,
                    'audit_name'=>$v->audit_name,
                    'order_audit_id'=>$v->id,
                ]);
        }
    }

    /**
     * 设置订单的生产状态
     */
    public function setOrderProductionStatus($order_id,$order_second_id,$production_status){
        if(!empty($order_second_id)){
            $order_second = OrderSecond::where('id',$order_second_id)->first();
            $order_second->production_status = $production_status;
            $order_second->save();
        }
        $order = Order::where('id',$order_id)->first();
        $order->production_status = $production_status;
        $order->save();
        return $order;
    }

    //自动生成流水号
    public function automaticGenerationSerialNumberRep($int = 1){
        $rule = \App\Models\RuleSerialNumber::first();
        $prefix = $rule->prefix_custom;
        if($rule->date == 1){
            $date = date("Y");
        }
        if($rule->date == 2){
            $date = date("Ym");
        }
        if($rule->date == 3){
            $date = date("Ymd");
        }
        $count = Order::whereBetween('created_at',[date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')])->count();
        $number = str_pad($count+$int,$rule->serial_number,"0",STR_PAD_LEFT);
        $serialNumber = $prefix.$date.$number;


        $info = Order::where('serial_number',$serialNumber)->first();
        if($info){
            $int = $int + 1;
            $serialNumber = $this->automaticGenerationSerialNumberRep($int);
        }
        //p($int);
        return $serialNumber;
    }

    //自动生成订单号
    public function automaticGenerationOrderNumberRep($int = 1){
        $order_count = Order::whereBetween('order_date',[date('Y-01-01'),date('Y-12-31')])->count();
        if($order_count>0){
            $order = Order::whereBetween('order_date',[date('Y-01-01'),date('Y-12-31')])
                ->orderBy('id','desc')
                ->first();
            $string = substr($order->order_number,2,5);
        }else{
            $string = $order_count;
        }
        $targetLength = 5;
        $paddingCharacter = "0";
        $result = str_pad($string+$int, $targetLength, $paddingCharacter,STR_PAD_LEFT);
        $order_number = substr(date("Y"),2,2).$result;
        $res = Order::where('order_number',$order_number)->first();
        if($res){
            $order_number = $this->automaticGenerationOrderNumberRep($int+1);
        }
        return $order_number;
    }

}
